<?php
/**
 * ArticleController
 * @copyright (c) 2011-2020, Hangzhou DOJI Tech Co., Ltd.
 * This is NOT a freeware, use is subject to license terms.
 * @package BaseRepository.php
 * @link https://www.tingjunapp.com/
 * @author wujun@lanqb.cn
 * @: ArticleController.php 310000 2020-11-011 15:07:29 $
 * */

namespace App\Http\Middleware;

use App\Models\Cache\CacheKey;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PcLoginCheck
{
    /**
     * Handle an incoming request.
     * 检查登录状态
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $userInfo = [];
        $token = $request->cookie('token') ? : $request->header('token');

        if ($token) {
            $login = repository()->LoginRepository->getModelByAccessToken($token);
            if (!$login) {
                $cacheUser = Cache::get(CacheKey::TOURIST . $token);
                $userInfo['userId'] = $cacheUser ? $cacheUser['id'] : '';
                $userInfo['identity'] = $cacheUser ? $cacheUser['identity'] : '';
                $userInfo['user'] = $cacheUser ? (object)$cacheUser : null;
            } else {
                // 如果user表没有查到，说明
                //  1. 游客
                //  2. 经过第三方登陆后，但没有绑定手机号的游客
                // 此时去缓存中查询：key： user:tourist:access_token
                if ($user = $login->user) {
                    $userInfo['userId'] = $user->id;
                    $userInfo['identity'] = $user->identity;
                    $userInfo['user'] = $user;
                } else {
                    $cacheUser = Cache::get(CacheKey::TOURIST . $token);
                    $userInfo['userId'] = $cacheUser ? $cacheUser['id'] : '';
                    $userInfo['identity'] = $cacheUser ? $cacheUser['identity'] : '';
                    $userInfo['user'] = $cacheUser ? (object)$cacheUser : null;
                }
            }
        } else {
            $userInfo = [
                'user' => '',
                'userId' => '',
                'identity' => '',
            ];
        }

        $request->merge(['userPcLogin' => $userInfo]);

        return $next($request);
    }
}
